<?php
//连接数据库
require_once("config/init.php");

//接收action参数
$action = isset($_GET['action']) ? trim($_GET['action']) : '';

//退出动作
if($action == "logout")
{
    session_destroy(); //清空所有的session数据
    notice("退出成功", "login.php");
    exit;
}

if($_POST)
{
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    $vercode = isset($_POST['vercode']) ? trim($_POST['vercode']) : '';

    //获取session中存放的验证码
    // $sess = isset($_SESSION['vercode']) ? trim($_SESSION['vercode']) : '';

    // if(empty($vercode) || empty($sess))
    // {
    //     notice('验证码不能为空');
    //     exit;
    // }

    // if(strtolower($vercode) != strtolower($sess))
    // {
    //     notice('验证码有误');
    //     exit;
    // }

    if(empty($username))
    {
        notice("用户名不能为空");
        exit;
    }

    if(empty($password))
    {
        notice('密码不能为空');
        exit;
    }

    //写sql语句查询用户是否存在
    $sql = "SELECT * FROM {$pre_}admin WHERE username = '$username'";
    $admin = find($sql);

    if(!$admin)
    {
        notice('管理员不存在');
        exit;
    }

    //如果存在，就验证密码是否正确
    $repass = md5($password.$admin['salt']); //明文密码+密码盐 一起md5加密

    //MD5加密的结果  如果 不等于数据库中存放的结果 就说明密码是错误的
    if($repass != $admin['password'])
    {
        notice('密码错误');
        exit;
    }

    //将这个管理员的用户信息存放在 session中
    $_SESSION['adminid'] = $admin['id'];
    $_SESSION['username'] = $admin['username'];

    notice("登录成功", "index.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <?php require_once('meta.php');?>
    </head>

    <body>
        <div class="navbar">
            <div class="navbar-inner">
                <a class="brand"><span class="second">通讯录</span></a>
            </div>
        </div>

        <div class="row-fluid">
            <div class="dialog">
                <div class="block">
                    <p class="block-heading">登录</p>
                    <div class="block-body">
                        <form method="post">
                            <label>用户名</label>
                            <input type="text" name="username" placeholder="请输入用户名" required class="span12" value="admin" />

                            <label>密码</label>
                            <input type="password" class="span12" name="password" placeholder="请输入密码" value="123123" required />

                            <label>验证码</label>
                            <input type="text" name="vercode" placeholder="请输入验证码" required class="span12" />

                            <img src="imgcode.php" style="width:150px;height:30px;" onclick="this.src=`imgcode.php?${Math.random()}`" />

                            <button type="submit" class="btn btn-primary pull-right">登录</button>
                            <div class="clearfix"></div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>